package com.huarui.area.init;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.InitializingBean;
import com.huarui.area.cash.AreaCashBean;
import com.huarui.area.dao.IAreaDao;
import com.huarui.area.model.Area;
import com.huarui.area.model.City;
import com.huarui.area.model.District;
import com.huarui.area.model.Province;
import com.huarui.area.model.Sector;

public class InitAreaBean implements InitializingBean {
	private IAreaDao areaDao;
	
	public void setAreaDao(IAreaDao areaDao) {
		this.areaDao = areaDao;
	}

	/**
	 * 启动服务是吧JSON对象加载到内存
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		List<Area> areas = this.areaDao.getAllArea();
		AreaCashBean.setAREA_MESS_JSON(this.getJsonByList(areas));
	}
	
	/**
	 * 封装json数据
	 * @param areas
	 * @return
	 */
	private JSONObject getJsonByList(List<Area> areas) {
		
		Set<String> ps = new HashSet<String>();
		for(Area a : areas) {
			ps.add(a.getProvince());
		}
		
		Map<String, String> cs = new HashMap<String, String>();
		for(Area a : areas) {
			cs.put(a.getCity(), a.getProvince());
		}
		
		Sector sector = new Sector();
		List<Province> pst = new ArrayList<Province>();
		sector.setProvinces(pst);
		Province _p = new Province("请选择", -2);
		List<City> _cst = new ArrayList<City>();
		_p.setCities(_cst);
		City _c = new City("请选择", -3);
		_cst.add(_c);
		List<District> _dst = new ArrayList<District>();
		_c.setDistricts(_dst);
		District _d = new District("请选择", -4);
		_dst.add(_d);
		pst.add(_p);
		
		for(String pnm : ps) {
			Province p = new Province(pnm, -1);
			List<City> cst = new ArrayList<City>();
			cst.add(_c);
			p.setCities(cst);
			pst.add(p);
			for(Entry<String, String> ety : cs.entrySet()) {
				if (ety.getValue().equals(pnm)) {
					City c = new City(ety.getKey(), 0);
					List<District> dst = new ArrayList<District>();
					dst.add(_d);
					c.setDistricts(dst);
					cst.add(c);
					for(Area a : areas) { 
						if (a.getCity().equals(ety.getKey())) {
							dst.add(new District(a.getDistrict(), a.getId()));
						}
					}
				}
				
			}
		}
		
		JSONObject jo = new JSONObject();
		jo.put("sector", sector);
//		System.out.println(jo.toString());
		return jo;
	}
	
	

}
